import time, os

import configparser, base64
from function import log, zuobiao
logger = log.log(__name__)
from function.json_to_obj import Dict2Obj as d2o

#获取当前时间
def getRealTimeHex():
    realTime = time.strftime('%y%m%d%H%M%S', time.localtime(time.time()))
    realLen = int(len(realTime)/2)
    _hexStr = [''.join([x for x in realTime[j*2:j*2+2]]) for j in range(realLen)]
    _hexStr = [hex(int(x)).replace('0x','').zfill(2) for x in _hexStr]
    _hexStr = ''.join(_hexStr)
    return  _hexStr
def getRealTime() ->list:
    realTime: str = time.strftime('%y-%m-%d-%H-%M-%S', time.localtime(time.time()))
    realTimeList: list  = [int(x) for x in realTime.split('-')]
    return realTimeList
def getRealTimeFlag():
    timeFlag = str(time.time()).replace('.','')
    # logger.info(len(timeFlag))
    return timeFlag
    
    
    
#实时里程计算
def mileage(meter):
    _meter = "".join("{:0>8x}".format((int(meter))))
    #logger.info(_meter)
    #time.sleep(100000)
    return _meter
	

#BCC异或校验
def bcc(data):
    # data = bytes.fromhex(data)
    retdata = 0
    for i in data:
        retdata ^= i
    #logger.info(retdata,'======================')
    #time.sleep(10000)
    return retdata

def autobcc(data):
    # if type(data) != type(b''):
    #     data = bytes.fromhex(data)
    '''
    :param data:传入字符串类型数据
    :return: 判断字符串校验结果，如果当前校验已通过，直接返回，如果为经过校验，添加校验位返回
    '''
    #logger.info('autobcc',data)
    retdata = bcc(bytes.fromhex(data))

    # #logger.info(data,'-----',retdata)
    
        ##logger.info('BCC校验码%s'% hex(retdata).replace('0x', ''))
    return data.lower() + hex(retdata).replace('0x', '').zfill(2) if retdata else data.lower()
    #return data


def sendmessage(s,data):
    #发送消息
    data = autobcc(bcc)
    
    s.send(data)
    return s.recv(1024)
def str_to_hex(data):
    # logger.info(data)
    dataList = [hex(x).replace('0x','').zfill(2) for x in data.encode()]
    redata = ''.join(dataList)
    #logger.info(redata)
    return redata
def hex_to_str(data):

    data = [hex(x).replace('0x','').zfill(2) for x in data]
    # return data
    return ''.join(data)
def int_to_hex(data,lenth=8):
    # logger.info(data,'===============')
    data = hex(data).replace('0x','').zfill(lenth)
    return  data
def get_input(msg='请输入字符串',_len= '', *args,**kraws):
    '''
    get_input()
    参数: msg: msg='请输入字符串'
    参数: *args
        _len = args[0] if args else 0
    参数: **kraws
        inpuType = kraws.get('inpuType',0)
        default = kraws.get('default',0)
    
    '''
    
    _len = kraws.get('len') if kraws.get('len') else _len
    inpuType = kraws.get('inpuType',0)
    default = kraws.get('default')
    defaultFlg = True if (default==0) else default
    # logger.info(default)
    input_str = input(msg)
    input_str = input_str.replace(' ','').replace('\t','').replace('\n','').replace('，',',')
    # 如果没输入并且有default, 打印并返回默认值
    if not input_str and defaultFlg  :
        logger.info(('没有输入,返回默认值default:   ',default))
        return default
    
    #logger.info(msg)
    # 如果_len不为空,并且输入的长度不等于_len, 重新输入
    if len(input_str) != _len and  _len:
            # raise Exception('输入字符串非法')
            input_str = get_input(f'输入长度不正确\n要求是{_len}, 实际是{len(input_str)},请重新输入:\t\t',_len, *args,**kraws)

    if not input_str:
        # 非空判断
        # logger.info('输入为空')
        return get_input(msg,*args,**kraws)
    if inpuType:
        try:
            input_str = inpuType(input_str)

        except Exception :
            input_str = get_input(f'输入字符类型不正确\n需要{inpuType}类型数据,当前是{type(input_str)}请重新输入',_len, *args,**kraws)

    return input_str 
    
def get_weizhi(local_Longitude_latitude: str)->list:
    '''传入经纬度字符串，[Longitude,latitude]'''
    # local_Longitude_latitude = zuobiao.bd09_to_wgs84(lat, lng)
    # logger.info(f"位置：\n\t{local_Longitude_latitude}")
    locaList: str = local_Longitude_latitude.split(',')
    # logger.info(locaList)
    # locaList: str = [x.split('.') for x in locaList]
    # locaList: str = [x.replace('.','') for x in locaList]
    # local_X_List: str = locaList[0]
    # logger.info(local_X_List)
    # local_Y_List: str = locaList[1]
    # local_X_str: int = int(''.join([local_X_List[0],local_X_List[1][0:6]]))
    # local_Y_str: int = int(''.join([local_Y_List[0],local_Y_List[1][0:6]]))
    
    local_Longitude_str,local_latitude_str = locaList
    local_Longitude_float,local_latitude_float = zuobiao.bd09_to_wgs84(float(local_Longitude_str),float(local_latitude_str) )
    logger.info(['wsg84',local_latitude_float, local_Longitude_float])
    local_Longitude_str: int  = round(local_Longitude_float*1000000)
    local_latitude_str: int = round(local_latitude_float*1000000)
    
    local_Longitude_str = int_to_hex(local_Longitude_str)
    local_latitude_str = int_to_hex(local_latitude_str)
    return local_Longitude_str, local_latitude_str
def wzModel(Longitude: float,
            miNum: float,
            maxNum: float
                )-> float:
    '''
    wzModel：传入经纬度
    在一个区间内循环
    '''
    flag = '+'
    logger.info('已加载完成')
    
    while True:

        
        if Longitude<maxNum and Longitude>miNum:
            # logger.info(f'tsp.Longitude {flag}= 0.0001')
            Longitude = Longitude+0.001 if flag=='+' else Longitude-0.001 
                
        elif Longitude>maxNum:
            flag = '-'
                
        elif Longitude<miNum:
            flag = '+'
        yield Longitude

class LoadConf():
    '''加载配置文件'''
    def __init__(self,fileName):
        # filepath = os.path.dirname(__file__)
        # file = os.path.abspath(os.path.join(filepath,'..','config',fileName))
        # file = os.sep.join((file, ))
        # self.fileName = file
        # logger.info(self.fileName)
        self.conf = configparser.ConfigParser()
        self.value = self.conf.read(fileName,encoding='utf-8')
    # def __getattribute__(self, name):
    #     return super().__getattribute__(name)
    # @classmethod 
    def loadConfIni(self,optionsStr):
        # import ConfigParser
        # logger.info("加载")

        # logger.info(value)]
        # logger.info(self.conf._sections)
        return d2o(self.conf._sections[optionsStr])
conf = LoadConf('conf.ini')
def strToBase64(Str:str)->'base64':
    '''base64转换'''
    base64Str = base64.b64encode(Str.encode())
    return base64Str.decode()
    









if __name__ == "__main__":
    # get_input(inpuType= int, )
    conf = LoadConf('conf.ini')
    iovConf = conf.loadConfIni('iovConf')
    defaultConf = conf.loadConfIni('defaultConf')

    logger.info(iovConf.user)
    logger.info(defaultConf.input_mileage)
    # logger.info(hex_to_str(b'##\xd1\xfeLNBSCB3F0JW176284\x01\x00\n\x13\x0b\x0f\x0f5"\x02=\x02\x01S'))
    # # logger.info(getRealTimeHex())
    # # loadConf('iovConf','user')
    # # logger.info(strToBase64('1'))
    # time.sleep(1000)
    # lat, lng = [39.9131293506,116.3808364607]
    # x, y = zuobiao.bd09_to_wgs84(lat, lng)
    # logger.info(x,y)
    # # x, y = get_weizhi('40.0780714275,116.7626953125')
    # # x, y = map(int_to_hex,(x,y))
    # logger.info(x, y )
    # logger.info(get_input('',0,default=123),'34555555555555555555555555555555')